<template>
	<!-- 对账单管理页面 -->
  <a-card :bordered="false">
		<!-- 顶部筛选 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" labelAlign="right">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="入库单号">
              <a-input v-model="queryParam.rkOrderNumber" placeholder="请输入"/>
            </a-form-item>
          </a-col>
					<a-col :md="8" :sm="24">
            <a-form-item label="采购单号">
              <a-input v-model="queryParam.cgOrderNumber" placeholder="请输入"/>
            </a-form-item>
          </a-col>
					<a-col :md="8" :sm="24">
            <a-form-item label="状态">
              <a-select allowClear v-model="queryParam.reconciliationStatus" placeholder="请选择">
                <a-select-option :value="item.value" v-for="(item, index) in statusList" :key="index">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="入库时间">
              <a-range-picker 
                style="width:100%"
                v-model="queryParam.timeList"
                format="YYYY-MM-DD"
							/>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-item label="供  应  商">
              <a-radio-group default-value="" button-style="solid" v-model="queryParam.orgIdSupplier">
                <a-radio-button value="">
                  全部
                </a-radio-button>
                <a-radio-button 
									:value="id"
                  v-for="{id, name} in $util.getOrgList([this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id, this.$businessEnum.ORG_TYPE_ENUM.NORMAL_SUPPLIER.id])"
									:key="id"
								>
                  {{ name }}
                </a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
					<a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button @click="queryParam={orgIdSupplier:''}; $refs.table.refresh(true)">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
		<!-- 按钮 -->
		<div style="color:#fff">
			<a-button style="background:#b2e81c;color: #fff;" @click="handleClickBtn(1)">对账完成</a-button>
			<a-button style="background:#1cd3e8;color: #fff;" @click="handleClickBtn(2)">开票完成</a-button>
			<a-button style="background:#1ce847;color: #fff;" @click="handleClickBtn(3)">付款完成</a-button>
      <Export
        text="导出"
        title="对账单列表"
        url="/emsOrder/reconciliationExport"
        :obj="{
          materialType: materialType,
          ...queryParam,
          startTime: appendTime(queryParam.timeList)[0],
          endTime: appendTime(queryParam.timeList)[1],
        }"
      />
		</div>
		
		<!-- 表格 -->
		<div style="display: flex;align-items:flex-end;justify-content: space-between;">
			<div class="selectText">
				<span>当前表格已选中 <span class="bold">{{ selectedRows.length }}</span> 项</span>
				<span style="cursor: pointer;" @click="clearSelect">清除</span>
			</div>
		</div>
    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :alert="true"
    >
			<span slot="selectBtn" slot-scope="text, record">
				<div 
					class="select-btn"
					:class="{
						'select-btn__selected': selectedRows.some(item=>item.sourceOrderId==record.sourceOrderId),
						'select-btn__disabled': selectedRows.length>0 && selectedRows[0].reconciliationStatus!==record.reconciliationStatus,
					}"
					@click="selectedRows.length>0&&selectedRows[0].reconciliationStatus!==record.reconciliationStatus ? '' : handleClickSelectBtn(record)"
				></div>
			</span>
			<span slot="reconciliationStatus"  slot-scope="text">
				<span 
					:style="{color: statusList.find(item=>item.value==text) ? statusList.find(item=>item.value==text).color : '--'}"
					style="font-weight: bold;"
				>
					{{ statusList.find(item=>item.value==text) ? statusList.find(item=>item.value==text).label : '' }}
				</span>
			</span>
			<!-- 操作 -->
      <span slot="action" slot-scope="text, record">
        <a-button type="link"  @click="$refs.addAndEdit.init(record)">详情</a-button>
      </span>
    </s-table>
    <!--  新增编辑详情弹框  -->
    <addAndEdit ref="addAndEdit"/>

  </a-card>
</template>

<script>
import {STable} from '@/components'
import {getUrlParam, MATERIAL_TYPE_ENUM, ORDER_TYPE_ENUM} from '@/utils/util'
import {
	page,
	reconciliation,  // 对账>>待开票
	invoicing,  // 开票>>待付款
	payment,  // 付款>>已完成
} from '@/api/modular/main/bill'
import addAndEdit from './addAndEdit'
       

export default {
  components: {
    STable,
    addAndEdit,
  },
	computed: {
		urlParam() {
			return getUrlParam(this.$route.path)
		},
		poolType() {
			return this.urlParam.poolType;
		},
		materialType() {
			return this.urlParam.materialType;
		},
		ORDER_TYPE_ENUM() {
			return ORDER_TYPE_ENUM;
		},
		materialTypeList() {
			let value = [{id: '', name: '全部', code: 'all'}]
			for (const key in MATERIAL_TYPE_ENUM) {
				value.push(MATERIAL_TYPE_ENUM[key])
			}
			return value
		},
	},
	watch: {
		'$route.path': function () {
			this.queryParam.materialType = this.urlParam.materialType
			setTimeout(() => {
				this.$refs.table.refresh(true)
				this.selectedRows.length = []
			}, 100)
		}
	},
  data() {
    return {
      queryParam: {},  // 查询参数
			selectedRows: [],
			statusList:[
				{label:'待对账',value:1, color:'#1cd3e8'},
				{label:'待开票',value:2, color:'#b2e81c'},
				{label:'待付款',value:3, color:'#f0aa13'},
				{label:'已完成',value:4, color:'#33ff33'},
			],
      columns: [
				{
					title: '', 
					width:'80px',
					scopedSlots: {customRender: 'selectBtn'}
				},
        {
          title: '序号',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '入库单号',
          dataIndex: 'rkOrderNumber'
        },
				{
          title: '采购单号',
          dataIndex: 'cgOrderNumber'
        },
        {
          title: '状态',
          dataIndex: 'reconciliationStatus',
					scopedSlots: {customRender: 'reconciliationStatus'}
        },
				{
          title: '供应商',
          dataIndex: 'supplierName'
        },
				{
          title: '发货时间',
          dataIndex: 'sendTime'
        },
				{
          title: '入库时间',
          dataIndex: 'warehousingTime'
        },
        {
          title: '操作',
					align:'center',
          width: '250px',
          scopedSlots: {customRender: 'action'}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
				let query = {
					...this.queryParam,
					...parameter,
					materialType: this.materialType,
          startTime: this.appendTime(this.queryParam.timeList)[0],
          endTime: this.appendTime(this.queryParam.timeList)[1],
				}
				delete query.timeList
        return page(query).then(res => {
          return res.data
        })
      },
      scheduleProductionVisible: false,
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
    }
  },
  methods: {
		handleClickBtn(e){
      let text = e==1 ? '待对账' : e==2 ? '待开票' : e==3 ? '待付款' : ''
			if(this.selectedRows.length == 0){
				return this.$message.error('请选择数据')
			}else if(this.selectedRows[0].reconciliationStatus!=e){
        return this.$message.error('请选择状态为 '+ text +' 的数据')
      }
			let query = {
				orderIds: this.selectedRows.map(item=>item.sourceOrderId)
			}
			// 1对账  2开票   3付款
			if(e == 1){
				reconciliation(query).then(res=>{
					this.$message.success('对账完成')
				})
			}else if(e == 2){
				invoicing(query).then(res=>{
					this.$message.success('开票完成')
				})
			}else if(e == 3){
				payment(query).then(res=>{
					this.$message.success('付款完成')
				})
			}
			this.selectedRows = []
			this.$refs.table.refresh()
		},
		// 清除选中
		clearSelect(){
				this.selectedRows = []
			},
		// 表格选择按钮点击事件
		handleClickSelectBtn(record){
			console.log()
			let i = this.selectedRows.findIndex(item=>item.sourceOrderId==record.sourceOrderId)
			if(i == -1){
				this.selectedRows.push(record)
			}else{
				this.selectedRows.splice(i, 1)
			}
		},
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
